package com.htdata.iiot.file.interceptor;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import com.htdata.iiot.file.dao.TenantDao;

@Component
public class HTInterceptor implements HandlerInterceptor {
	private static final String TENANT_API_KEY = "apiKey";

    private Logger logger = LogManager.getLogger(HTInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception{
    	response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "*");
    	
		boolean checkAuth = checkAuth(request, response, obj);
		if(!checkAuth){
			
			if(obj instanceof ResourceHttpRequestHandler){
				request.getRequestDispatcher("/noauth.png").forward(request, response);
			}else{
				response.getWriter().write("no auth");
			}
			return false;
			
		}
		return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object obj, ModelAndView mv) throws Exception{
    	
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception exception) throws Exception{
    }
    
    
    protected int getRequestTenantId(HttpServletRequest request) {

		String uri = request.getRequestURI();
		String regHost = "^/[0-9]\\d*/";
		Pattern r = Pattern.compile(regHost);
		Matcher matcher = r.matcher(uri);
		int tenantId = -1;
		if (matcher.find()) {
			String group = matcher.group(0);
			String tenantIdStr = group.substring(1, group.length() - 1);
			try {
				tenantId = Integer.parseInt(tenantIdStr);
			} catch (NumberFormatException e) {
				e.printStackTrace();
			}
		}

		return tenantId;
	}
    
    
    private boolean checkAuth(HttpServletRequest request, HttpServletResponse response, Object obj){
    	
    	String uri =  request.getRequestURI();
    	logger.info(uri);
		int tenantId = -1;
		tenantId = getRequestTenantId(request);
		String tenantIdStr = request.getParameter("tenantId");
		if(tenantId==-1&&null!=tenantIdStr){
			tenantId = Integer.parseInt(tenantIdStr);
		}
		
		//ssologin
		
		/* if (!SsoLogin.isLogin(request.getSession())) {
            String retUrl = request.getRequestURI();
            String queryString = request.getQueryString();
            if (!StringUtils.isEmpty(queryString)){
            	retUrl += "?" + queryString;
            }
            response.sendRedirect(SsoLogin.getLoginUrl(request, retUrl));
	        return false;
	      }*/
		
		if(tenantId>0){
			
			String apiKey = request.getHeader(TENANT_API_KEY);
			String token = request.getParameter("token");
			String tsStr = request.getParameter("ts");
			if(apiKey==null&&(token==null||tsStr==null)){
				return false;
			}
			
			String apiKey2 = TenantDao.getTenantById(tenantId);
			
			if(apiKey!=null){
				if(!apiKey.equals(apiKey2)){
					return false;
				}
			}else{
				long ts = Long.parseLong(tsStr);
				long now = System.currentTimeMillis();
				if(Math.abs(now-ts)>5*60*1000){
					return false;
				}
				String decrypt=tenantId+"+"+apiKey2+"+"+tsStr;
		        String encrpyPwd = DigestUtils.sha1Hex(decrypt);
				if(!encrpyPwd.equals(token)){
					return false;
				}
			}
			
		}

		return true;
    }

}